package com.Alan.servlet.user;

import com.Alan.dao.user.UserDaoImpl;
import com.Alan.pojo.Role;
import com.Alan.pojo.User;
import com.Alan.service.role.RoleService;
import com.Alan.service.role.RoleServiceImpl;
import com.Alan.service.user.UserService;
import com.Alan.service.user.UserServiceImpl;
import com.Alan.util.Constants;
import com.Alan.util.Paging;
import com.Alan.util.UtilsAlan;
import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @CreateDate 2021/8/14 18:23
 */
public class UserServlet extends HttpServlet {

    public UserServlet() {
        super();
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        System.out.println("method : " + method);
        if (method != null) {
            switch (method) {
                case "updatePassword":
                    this.updatePassword(req, resp);
                    break;
                case "validationOldPassword":
                    this.validationOldPassword(req, resp);
                    break;
                case "getUserList":
                    this.getUserList(req, resp);
                    break;
                case "verifyUserCodeExist":
                    this.verifyUserCodeExist(req, resp);
                    break;
                case "getRoleList":
                    this.getRoleList(req, resp);
                    break;
                case "addUser":
                    this.addUser(req, resp);
                    break;
                case "userInformation":
                    this.userInformation(req, resp);
                    break;
                case "updateUser":
                    this.updateUser(req, resp);
                    break;
                case "updateUserSubmit":
                    this.updateUserSubmit(req, resp);
                    break;
                case "deleteUser":
                    this.deleteUser(req, resp);
                    break;
            }
        }
    }

    private void updatePassword(HttpServletRequest req, HttpServletResponse resp) {
        Object user = req.getSession().getAttribute(Constants.USER_SESSION);
        String newPassword = req.getParameter("newPassword");

        if (user != null && !StringUtils.isNullOrEmpty(newPassword)) {
            UserService userService = new UserServiceImpl();
            int id = ((User) user).getId();
            if (userService.update(id, newPassword)) {
                req.setAttribute(Constants.MESSAGE, "密码修改成功,请使用新密码重新登录");
//                修改成功移除session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            } else {
                req.setAttribute(Constants.MESSAGE, "密码修改失败,请重试");
            }
        } else {
            req.setAttribute(Constants.MESSAGE, "输入密码有问题，修改失败");
        }

        try {
            req.getRequestDispatcher(req.getContextPath() + "/JSP/updatePassword.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("UpdateServlet--save错误");
        }
    }

    private void validationOldPassword(HttpServletRequest req, HttpServletResponse resp) {
        Object user = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldPassword = req.getParameter("oldPassword");
        Map<String, String> map = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(oldPassword)) {
            map.put("result", "empty");
        } else if (user == null) {
            map.put("result", "sessionError");
        } else {
            String password = ((User) user).getUserPassword();
            if (password.equals(oldPassword)) {
                map.put("result", "true");
            } else {
                map.put("result", "false");
            }
        }

        resp.setContentType("application/json");
        try {
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(map));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("UpdateServlet--validation错误");
        }
    }

    private void getUserList(HttpServletRequest req, HttpServletResponse resp) {

//        创建工具类
        Paging paging = new Paging();

//        从前端获取数据
        String userName = req.getParameter("queryUserName");
        String queryUserRole = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");

        int userRole = 0;

//        第一次进入用户管理页面，queryUserName，queryUserRole，pageIndex都是空
        if (StringUtils.isNullOrEmpty(userName)) {
            userName = "";
        }
        if (!StringUtils.isNullOrEmpty(queryUserRole)) {
            userRole = Integer.parseInt(queryUserRole);
        }
        if (!StringUtils.isNullOrEmpty(pageIndex)) {
            paging.setPageIndex(Integer.parseInt(pageIndex));
        }

//        获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = userService.getUserList(userName, userRole, paging.getStartRow(), paging.getPageRows());
//        获取用户总数并添加到Paging
        int userCount = userService.getCount(userName, userRole);
        paging.setAllSize(userCount);
//        获取角色列表
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList(0);

//        返回前端数据
        req.setAttribute("userList", userList);
        req.setAttribute("roleList", roleList);
        req.setAttribute("pageCount", paging.getPageCount());
        req.setAttribute("allSize", paging.getAllSize());
        req.setAttribute("pageIndex", paging.getPageIndex());
        req.setAttribute("queryUserRole", queryUserRole);
        req.setAttribute("queryUserName", userName);
        req.setAttribute("nowUserRole", ((User)req.getSession().getAttribute(Constants.USER_SESSION)).getUserRole());

//        返回前端
        try {
            req.getRequestDispatcher(req.getContextPath() + "/JSP/userList.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("UserServlet -> Line(140)");
        }


    }

    private void verifyUserCodeExist(HttpServletRequest req, HttpServletResponse resp) {
        String userCode = req.getParameter("userCode");
        HashMap<String, String> resultMap = new HashMap<String, String>();

        if (!StringUtils.isNullOrEmpty(userCode)) {
            UserService userService = new UserServiceImpl();
            User user = userService.login(userCode);
            if (user == null) {
                resultMap.put("userCode", "notExist");
            } else {
                resultMap.put("userCode", "exist");
            }
        } else {
            resultMap.put("userCode", "exist");
        }

        //把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        resp.setContentType("application/json");
        //从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = null;
        try {
            outPrintWriter = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("UserServlet -> verifyUserCodeExist");
        }
        //把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();//刷新
        outPrintWriter.close();//关闭流
    }

    private void getRoleList(HttpServletRequest req, HttpServletResponse resp) {
        RoleService roleService = new RoleServiceImpl();
        int userRoleNow = ((User)req.getSession().getAttribute(Constants.USER_SESSION)).getUserRole();
        List<Role> roleList = roleService.getRoleList(userRoleNow);
//        返回json格式
        resp.setContentType("application/json; charset=UTF-8");
        try {
            PrintWriter outPrintWriter = resp.getWriter();
            outPrintWriter.write(JSONArray.toJSONString(roleList));
            outPrintWriter.flush();
            outPrintWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("UserServlet -> getRoleList");
        }
    }

    private void addUser(HttpServletRequest req, HttpServletResponse resp) {
        User user = new User();
        user.setUserCode(req.getParameter("userCode"));
        user.setUserName(UtilsAlan.transCoding(req.getParameter("userName"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        user.setUserPassword(req.getParameter("userPassword"));
        user.setGender(UtilsAlan.transCoding(req.getParameter("userGender"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        user.setBirthday(UtilsAlan.strToSqlDate(req.getParameter("userBirthday"), false));
        user.setPhone(req.getParameter("userPhone"));
        user.setAddress(UtilsAlan.transCoding(req.getParameter("userAddress"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        user.setUserRole(Integer.parseInt(req.getParameter("userRole")));
        user.setCreatedByUserCode(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getUserCode());
        user.setCreatedByUserName(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getUserName());
        user.setCreationDate(UtilsAlan.strToSqlDate(UtilsAlan.getNowDateStr(), true));

        System.out.println("获取前端数据成功");
        UserService userService = new UserServiceImpl();
        if (userService.addUser(user)) {
            try {
                resp.sendRedirect(req.getContextPath() + "/JSP/user.go?method=getUserList");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("UserServlet -> addUser -> Line(247)");
            }
        } else {
            try {
                req.getRequestDispatcher(req.getContextPath() + "/JSP/userAdd.jsp").forward(req, resp);
                req.setAttribute(Constants.MESSAGE, "添加失败，请退出重试");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("UserServlet -> addUser -> Line(254)");
            }
        }
    }

    private void userInformation(HttpServletRequest req, HttpServletResponse resp) {
        int userId = Integer.parseInt(req.getParameter("userId"));
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.getUserInformation(userId);
        req.setAttribute("user", user);
        try {
            req.getRequestDispatcher(req.getContextPath() + "/JSP/userInformation.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERROR:UserServlet -> userInformation");
        }
    }

    private void updateUser(HttpServletRequest req, HttpServletResponse resp) {
        int userId = Integer.parseInt(req.getParameter("userId"));
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.getUserInformation(userId);
        req.setAttribute("user", user);
        try {
            req.getRequestDispatcher(req.getContextPath() + "/JSP/updateUser.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERROR:UserServlet -> updateUser");
        }
    }

    private void updateUserSubmit(HttpServletRequest req, HttpServletResponse resp) {
        User user = new User();
        user.setId(Integer.parseInt(req.getParameter("userId")));
        user.setUserName(req.getParameter("userName"));
        user.setGender(UtilsAlan.transCoding(req.getParameter("userGender"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        user.setBirthday(UtilsAlan.strToSqlDate(req.getParameter("userBirthday"), false));
        user.setPhone(req.getParameter("userPhone"));
        user.setAddress(UtilsAlan.transCoding(req.getParameter("userAddress"), UtilsAlan.ISO_8859_1, UtilsAlan.UTF_8));
        user.setUserRole(Integer.parseInt(req.getParameter("userRole")));
        user.setModifyByUserCode(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getUserCode());
        user.setModifyByUserName(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getUserName());
        user.setModifyDate(UtilsAlan.strToSqlDate(UtilsAlan.getNowDateStr(), true));

        UserService userService = new UserServiceImpl();

        if (userService.updateUser(user)) {
            System.out.println("true");
            try {
                resp.sendRedirect(req.getContextPath() + "/JSP/user.go?method=getUserList");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("UserServlet -> updateUserSubmit");
            }
        } else {
            System.out.println("false");
            try {
                req.getRequestDispatcher(req.getContextPath() + "/JSP/updateUser.jsp").forward(req, resp);
                req.setAttribute(Constants.MESSAGE, "修改失败，请退出重试");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("UserServlet -> updateUserSubmit");
            }
        }


    }

    private void deleteUser(HttpServletRequest req, HttpServletResponse resp) {
        int userId = Integer.parseInt(req.getParameter("userId"));
        UserService userService = new UserServiceImpl();
        if (userService.delelteUser(userId)){
            try {
                resp.sendRedirect(req.getContextPath() + "/JSP/user.go?method=getUserList");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("ERROR:UserServlet -> deleteUser -> Line(351)");
            }
        }else {

        }
    }


}
